#include<mysql/mysql.h>
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
const char *host = NULL;
const char *user = "root";
const char *passwd = NULL;
const char *db = "11_30";
unsigned int port = 0;
const char *unix_socket = NULL;
unsigned long clientflag = 0;

void mysql_module()
{
    //初始化
    MYSQL* mysql_ = mysql_init(NULL);
    //建立连接
    if(mysql_real_connect(mysql_, host, user, passwd, db, port, unix_socket, clientflag)==NULL){
        cout<<"连接错误"<<endl;
        cout<<mysql_errno(mysql_)<<endl;
        exit(-1);
    }
    mysql_set_character_set(mysql_, "utf8"); // 设置默认字符集

    //查询语句
    const char* stmt_str="select* from stu";
    if(mysql_real_query(mysql_,stmt_str,strlen(stmt_str))!=0){
        cout<<"执行查询失败"<<endl;
        cout<<mysql_errno(mysql_)<<endl;
        exit(-1);
    }

    //获取查询结果保存在MYSQL_RES中
    MYSQL_RES* res=NULL;
    res = mysql_store_result(mysql_);
    if(res==NULL){
        perror("返回结果集失败或者为空");
        printf("%u\n",mysql_errno(mysql_));
        exit(-1);
    }

    uint64_t rows = mysql_num_rows(res);//获取行数
    unsigned int cols = mysql_num_fields(res);//获取列数
    MYSQL_FIELD * filed = mysql_fetch_fields(res);//获取列名
    cout<<"行："<<rows<<endl;
    cout<<"列："<<cols<<endl;
    //打印结果集
    for(int i=0;i<cols;i++){
        printf("%s ",filed[i].name);
    }
    printf("\n");
    for(int i=0;i<rows;i++){
        MYSQL_ROW content = mysql_fetch_row(res);//获取结果内容
        for(int j=0;j<cols;j++)
            printf("%s ",content[j]);
        printf("\n");
    }
    mysql_close(mysql_);//关闭连接
}
int main(){
    mysql_module();
    return 0;
}
